package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.*;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private AttrDao attrDao;

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }



    @Override
    public PageUtils getnoGroupAttr(Map<String, Object> params, Long attrGroupId) {

        //查出分组所属分类id
        AttrGroupEntity groupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = groupEntity.getCatelogId();
        System.err.println("catelogId:"+catelogId);


        //查出分类中所有分组
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catelogId));
        List<Long> groupIds = attrGroupEntityList.stream().map((attrGroupEntity) -> {
            Long  groupId= attrGroupEntity.getAttrGroupId();
            return groupId;
        }).collect(Collectors.toList());
        System.err.println("attrGroupEntityList:"+attrGroupEntityList.toString());
        System.err.println("groupIds:"+groupIds.toString());
        //查出分组中所有已关联属性id
        if(groupIds!=null)
        {
            List<AttrAttrgroupRelationEntity> relationEntities1 = attrgroupRelationDao.selectList(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id",groupIds));
            System.err.println("relationEntities1:"+relationEntities1.toString()+" "+relationEntities1.size());
            List<Long> attrIds = relationEntities1.stream().map((relationEntity) -> {
                return relationEntity.getAttrId();
            }).collect(Collectors.toList());
            System.err.println("attrIds:"+attrIds.toString()+" "+attrIds.size());

            //查询未关联的属性
            QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
            if(attrIds!=null &&attrIds.size()>0){
                System.err.println("我进入notIn:"+attrIds.size());
                queryWrapper.notIn("attr_id", attrIds);
            }

            //拼接搜索key
            String key = (String) params.get("key");
            if(!StringUtils.isEmpty(key)){
                queryWrapper.and((w)->{
                    w.eq("attr_id",key).or().like("attr_name",key);
                });
            }

            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),queryWrapper);

                PageUtils pageUtils = new PageUtils(page);
                return  pageUtils;
        }

        //查出分类关联的所有属性


        return null;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.baseMapper.insert(attrEntity);

        if(attrVo.getAttrType()== ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId()!=null){
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            if(attrVo.getAttrGroupId()!=null){
                attrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                attrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrgroupRelationDao.insert(attrgroupRelationEntity);
            }
        }


    }

    @Override
    public PageUtils queryBaseAttr(Map<String, Object> params, Long catelogId, String type) {

        //此处判断是否为基础属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?1:0);

        if(catelogId!=0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");

        if(!StringUtils.isEmpty(key)){
            queryWrapper.eq("attr_id",key).or().like("attr_name",key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> pageRecords = page.getRecords();

        List<AttrRespVo> respVos = pageRecords.stream().map((records) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(records, attrRespVo);

            CategoryEntity categoryEntity = categoryDao.selectById(records.getCatelogId());
            if(categoryEntity!=null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            if("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", records.getAttrId()));
                //System.out.println("relationEntity.getAttrGroupId():"+relationEntity.getAttrGroupId());
                if( relationEntity!=null){
                    AttrGroupEntity groupEntity = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", relationEntity.getAttrGroupId()));
                    if(groupEntity!=null){
                        attrRespVo.setAttrGroupName(groupEntity.getAttrGroupName());
                    }

                }
            }
            return attrRespVo;

        }).collect(Collectors.toList());

        if (respVos!=null){
            pageUtils.setList(respVos);
            return pageUtils;
        }

        return null;
    }

    @Override
    public AttrRespVo attrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = attrDao.selectById(attrId);
        BeanUtils.copyProperties(attrEntity,respVo);

        //属性表不为空
        if(attrEntity!=null){
            List<Long> catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
            System.err.println("catelogPath值："+catelogPath);
            respVo.setCatelogPath(catelogPath);
        }

        if(attrEntity.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //属性与分组关联表不为空
            AttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if(relationEntity!=null && relationEntity.getAttrGroupId()!=null){
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                respVo.setAttrGroupId(relationEntity.getAttrGroupId());
                System.err.println("attrGroupEntity.getAttrGroupName()值："+attrGroupEntity.getAttrGroupName());
                respVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());

            }
        }


        //分类表不为空
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if(categoryEntity!=null){
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }


    @Transactional
    @Override
    public void updateAttrInfo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        attrDao.updateById(attrEntity);


        //创建（AttrAttrgroupRelationEntity）更新实体,当更新基础属性时才做
        if(attr.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //根据attr条件更新关联表
            attrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

        }

    }

}